package org.ee.core.util;

import org.ee.core.security.UserPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 通用安全工具类
 * 获取当前用户信息(用户名/ID）
 * @Author jokr
 * @Date 2025/8/29 09:57
 */
public class SecurityUtil {

    /**
     * 获取当前登录用户对象
     * @return userProvincial
     */
    public static Optional<UserPrincipal> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return Optional.empty();
        }

        Object principal = authentication.getPrincipal();

        if (principal instanceof UserPrincipal user) {
            return Optional.of(user);
        }

        return Optional.empty();
    }
    /**
     * 获取当前登录用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }

        Object principal = authentication.getPrincipal();

        if(principal instanceof UserPrincipal) {
            return ((UserPrincipal) principal).getCurrentUsername();
        }else if(principal instanceof String) {
            return (String) principal;
        }
        return null;
    }

    /**
     * 获取当前登录用户ID
     * 需要在认证成功时，把用户ID放进 principal 或者 details
     */
    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }

        Object principal = authentication.getPrincipal();

        if(principal instanceof UserPrincipal) {
            return ((UserPrincipal) principal).getCurrentUserId();
        }

        return null;
    }

    /**
     * 判断是否已登录
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated()
                && !"anonymousUser".equals(authentication.getPrincipal());
    }
}
